import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

export default {
  install(Vue, options) {
    Vue.prototype.getHengPdf = function (options = {}) {
      return new Promise((resolve, reject) => {
        const config = {
          download: true,
          format: "png",
          quality: 0.1, // 1.0 最大
          ...options,
        };

        const title = this.tableTitle || "document";

        html2Canvas(document.querySelector("#pdfHengDom"), {
          scale: 1, // 可根据需要调整清晰度
          allowTaint: true,
          useCORS: true,
          backgroundColor: null,
        })
          .then((canvas) => {
            const mimeType = config.format === "jpeg" ? "image/jpeg" : "image/png";
            const base64Image = canvas.toDataURL(mimeType, config.quality);

            // 保存 base64 到实例
            this.pdfBase64 = base64Image;

            // ========== 生成横向 PDF ==========

            const contentWidth = canvas.width;
            const contentHeight = canvas.height;

            // 横向 A4 尺寸（pt）：841.89 × 595.28
            const pageWidth = 841.89;  // 横向页面宽度
            const pageHeight = 595.28; // 横向页面高度
            const imgWidth = pageWidth;
            const imgHeight = (pageWidth / contentWidth) * contentHeight;

            // 创建横向 PDF 实例
            const PDF = new JsPDF("landscape", "pt", "a4"); // 关键：设置为 landscape

            let position = 0;
            let remainingHeight = contentHeight;

            if (imgHeight <= pageHeight) {
              // 单页即可容纳
              PDF.addImage(base64Image, config.format.toUpperCase(), 0, 0, imgWidth, imgHeight);
            } else {
              // 多页处理
              while (remainingHeight > 0) {
                PDF.addImage(
                  base64Image,
                  config.format.toUpperCase(),
                  0,
                  position,
                  imgWidth,
                  imgHeight
                );
                remainingHeight -= pageHeight;
                position -= pageHeight;
                if (remainingHeight > 0) {
                  PDF.addPage();
                }
              }
            }

            // 输出为 Blob
            const pdfBlob = PDF.output("blob");
            // console.log("pdf", pdfBlob);

            // 是否自动下载
            if (config.download) {
              PDF.save(title + ".pdf");
            }

            // 成功返回 Blob
            resolve(pdfBlob);
          })
          .catch((err) => {
            console.error("html2canvas error:", err);
            reject(err);
          });
      });
    };
  },
};